<template>
  <div>
    <VueJsonSchemaItem
      v-for="(item, index) in schemas"
      :key="index"
      :initialSchema="item"
      :data="data"
    >
    </VueJsonSchemaItem>
  </div>
</template>

<script lang="ts">
import {ref, defineComponent, provide} from 'vue';
import VueJsonSchemaItem from './VueJsonSchemaItem.vue';

// 存储动态注册的组件
const components: Record<string, any> = {};
// 存储模版引用的组件
const dynamicRefs: Record<string, any> = {};
// 注册组件
export const registerComponent = (componentName: string, component: any) => {
  if (components[componentName]) {
    console.warn(`Component ${componentName} has already been registered.`);
    return;
  }
  components[componentName] = component;
};

interface JsonSchema {
  com: string;
  comId?: string; // 模版引用字符串
  data?: Record<string, any>; // 数据
  props?: Record<string, any>; // 属性
  modelValue?: string; // 绑定值
  events?: Record<string, any>; // 事件
  body?: string | JsonSchema[]; // 支持字符串或数组作为默认插槽内容
  slots?: Record<string, any>; // 定义具名插槽名称和内容
  beforeMount?: string; // 组件挂载前执行
  mounted?: string; // 组件挂载完成后执行
  beforeUpdate?: string; // 组件更新前执行
  updated?: string; // 组件更新完成后执行
  beforeUnmount?: string; // 组件卸载前执行
  unmounted?: string; // 组件卸载完成后执行
}

export default defineComponent({
  name: 'VueJsonSchema',
  props: {
    initialSchema: {
      type: Array as () => Array<JsonSchema>,
      required: true,
    },
    data: {
      type: Object,
      default: {},
    },
  },
  components: {
    VueJsonSchemaItem
  },
  setup(props) {
    const schemas = ref([...props.initialSchema]);
    provide('zugoComponents', components);
    provide('dynamicRefs', dynamicRefs);
    // 判断组件是否已注册
    const isComponentRegistered = (componentName: string) => {
      console.log('components.value', componentName, componentName in components.value);
      return componentName in components.value;
    };

    return {
      schemas,
      components,
      isComponentRegistered
    };
  },
});
</script>

<style scoped>
/* 添加样式 */
</style>